<?php
/**
 * @author Vincent
 * @desc 容联.云通讯 - 短信
 * @document http://www.yuntongxun.com/doc/rest/sms/3_2_2_2.html
 */

namespace young;

class RL
{
    private $AccountSid;
    private $Token;
    private $AppId;
    private $Batch;

    /**
     * RL constructor.
     * @param $AccountSid 开发者主账户ACCOUNT SID
     * @param $Token 账户授权令牌
     * @param $AppId 应用Id
     */
    public function __construct($AccountSid, $Token, $AppId)
    {
        $this->AccountSid = $AccountSid;
        $this->Token = $Token;
        $this->AppId = $AppId;
        $this->Batch = date("YmdHis");
    }

    /**
     * @param $to 短信接收端手机号码集合，用英文逗号分开，每批发送的手机号数量不得超过200个
     * @param array $options 内容数据外层节点，模板如果没有变量，此参数可不传
     * @param $tempId 模板Id
     * @return array|bool
     */
    public function sms($to, $options = [], $tempId)
    {

        $apiUrl = 'https://app.cloopen.com:8883/2013-12-26/Accounts/' . $this->AccountSid . '/SMS/TemplateSMS?sig=' . $this->SigParameter();
        $body = [
            'to' => $to,
            'templateId' => $tempId,
            'appId' => $this->AppId,
            'datas' => $options
        ];
        $body = json_encode($body);
        $header = array("Accept:application/json", "Content-Type:application/json;charset=utf-8", "Authorization:{$this->Authorization()}");
        $result = $this->request($apiUrl, $body, $header);
        $result = json_decode($result, true);
        if ($result['statusCode'] == '000000') {
            return true;
        } else {
            return $this->error($result['statusCode'], $result['statusMsg']);
        }
    }

    private function error($code, $msg)
    {
        return ['code' => $code, 'msg' => $msg];
    }

    private function SigParameter()
    {
        return strtoupper(md5($this->AccountSid . $this->Token . $this->Batch));
    }

    private function Authorization()
    {
        return base64_encode($this->AccountSid . ":" . $this->Batch);
    }

    private function request($url, $body, $header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}